<script setup lang="ts">
import {
    NButton,
    NSpace,
    NDataTable,
    NInput,
    type DataTableColumns,
    NPagination,
    NForm,
    NFormItem,
    NModal,
    NSelect,
    useMessage,
    NDatePicker
} from 'naive-ui'
import { h, onMounted, reactive, watch, ref } from 'vue'
import TableView from '@/components/TableView.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination, HttpResponse } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { useRouter, useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import dayjs from 'dayjs'
import { RecordType } from '@/router/utils'

const message = useMessage()
const router = useRouter()
const route = useRoute()

const modalVisible = ref<boolean>(false)
const revokeId = ref<string | null>(null)

const paginationReactive = reactive({
    date: null,
    userId: -1,
    purpose: null,
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    onChange: (page: number) => {
        paginationReactive.page = page
        queryTableData()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        queryTableData()
    }
})
//部门人员
const partList: any = ref([])
const getPartName = async () => {
    const [error, res] = await sendRequest({
        module: 'office',
        api: 'partPersons',
        override: {
            params: {
                deptId: null
            }
        }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    partList.value = [{ value: -1, label: '所有' }, ...res.data.map((r: any) => {
        return {
            label: r.name,
            value: r.value
        }
    })]
}
const exportLoading = ref<boolean>(false)
const exportFile = async () => {
    exportLoading.value = true
    const [error, res, headers] = await sendRequest<HttpResponse>({
        module: 'digitalCollect',
        api: 'deptListExport',
        override: {
            params: {
                limit: 99999,
                page: paginationReactive.page,
                startUsageTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
                endUsageTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
            }
        }
    })
    if (error) return message.error(error.message), (exportLoading.value = false)
    download(headers, res, '部门请假统计')
    message.success('导出成功')
    exportLoading.value = false
}
const tableData = ref<InterpreterModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
    if (flush) paginationReactive.page = 1
    try {
        tableLoading.value = true
        const [error, res] = await sendRequest<HttpResponsePagination<InterpreterModel>>({
            module: 'digitalCollect',
            api: 'deptList',
            override: {
                params: {
                    limit: paginationReactive.pageSize,
                    page: paginationReactive.page,
                    startUsageTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
                    endUsageTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
                    userId: paginationReactive.userId === -1 ? null : [paginationReactive.userId],
                    purpose: paginationReactive.purpose
                }
            }
        })
        if (error) throw error
        if (res.code !== 0) throw new Error(res.msg)
        tableData.value = res.data.list.map((r: any) => {
            return {
                ...r,
                exportLoading: false
            }
        })
        paginationReactive.itemCount = res.data.totalCount
    } catch (error) {
        console.log(error)
    } finally {
        tableLoading.value = false
    }
}
// 撤回消息
const revoke = async () => {
    const [error, res] = await sendRequest<HttpResponse>({
        module: 'receiveOrDispatch',
        api: 'dispatchRevoke',
        override: {
            data: {
                functionCode: 'A0576',
                resourceId: revokeId.value
            }
        }
    })
    if (error) return message.error('撤回失败'), (modalVisible.value = false)
    if (res.code !== 0) return message.error('撤回失败'), (modalVisible.value = false)
    message.success('撤回成功')
    modalVisible.value = false
    queryTableData()
}
// 单条记录导出
const exportSingle = async (id: string) => {
    tableData.value.forEach((t: any) => {
        t.exportLoading = (String(t.id) === id)
    })
    const [error, data, headers] = await sendRequest<HttpResponse>({
        module: 'digitalCollect',
        api: 'exportSingle',
        uri: {
            id
        }
    })
    if (error) {
        tableData.value.forEach((t: any) => {
            t.exportLoading = false
        })
        message.error("导出出错")
        throw new Error("导出出错")
    }
    tableData.value.forEach((t: any) => {
        t.exportLoading = false
    })
    download(headers, data, '杭州国家版本馆数字版本提用申请单')
    message.success("导出成功")
}
//导出
function download(headers: any, data: any, name?: string) {
    const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
    let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
    if (!filename.includes('xlsx')) {
        filename = filename.replace('xls', 'xlsx')
    }
    const a = document.createElement('a')
    let binaryData = []
    binaryData.push(data)
    a.href = window.URL.createObjectURL(new Blob(binaryData))
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(a.href)
}

const columns: DataTableColumns<InterpreterModel> = [
    {
        title: '申请人',
        key: 'userName',
        align: 'center'
    },
    {
        title: '申请人部门',
        key: 'deptName',
        align: 'center'
    },
    {
        title: '使用时间',
        key: 'date',
        align: 'center',
        render: (row: any, index: number) => {
            if (!row.startUsageTime) {
                return ''
            }
            return `${row.startUsageTime.split(" ")[0]} 至 ${row.endUsageTime.split(" ")[0]}`
        }
    },
    {
        title: '用途',
        key: 'purpose',
        align: 'center'
    },
    {
        title: '申请时间',
        key: 'createTime',
        align: 'center'
    },
    {
        title: '操作',
        key: 'operation',
        align: 'center',
        render: (row: any, index) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: () => {
                        RecordType.setRouteNameTypeFalse('A0576')
                        router.push({ path: '/OA/digitalCollect/detail', query: { id: row.id } })
                    }
                },
                {
                    default: () => '详情'
                }
            ),
            row.fromStatusCode === 'A0605' && h(
                NButton,
                {
                    type: 'info',
                    quaternary: true,
                    loading: row.exportLoading || false,
                    onClick: () => {
                        exportSingle(String(row.id))
                    }
                },
                {
                    default: () => '导出'
                }
            )
        ]
    }
]

watch(
    () => route,
    async () => {
        if (route.path == '/OA/DigitalCollect/deptDigitalCollect') {
            await getPartName()
            queryTableData(true)
        }
    },
    { deep: true, immediate: true }
)

</script>

<template>
    <div class="interpreter_record_container">
        <div class="interpreter_record_form">
            <NSpace justify="space-between">
                <NForm ref="formRef" inline label-placement="left" :model="paginationReactive">
                    <NFormItem label="统计月份：" path="date">
                        <NDatePicker v-model:value="paginationReactive.date" type="daterange" clearable />
                    </NFormItem>
                    <NFormItem label="部门人员:">
                        <NSelect :options="partList" v-model:value="paginationReactive.userId" placeholder="请选择部门人员"
                            clearable style="width: 200px" filterable />
                    </NFormItem>
                    <NFormItem label="用途:">
                        <NInput :options="partList" v-model:value="paginationReactive.purpose" placeholder="请输入用途"
                            clearable style="width: 200px" />
                    </NFormItem>
                    <NFormItem>
                        <NButton style="margin-right: 10px;" ghost type="primary" @click="queryTableData(false)">
                            查询
                        </NButton>
                    </NFormItem>
                </NForm>
                <NSpace align="end">
                    <NButton type="primary" ghost style="width: 115rem" @click="exportFile" :loading="exportLoading">
                        导出
                    </NButton>
                </NSpace>
            </NSpace>
        </div>
        <div class="interpreter_record_table">
            <NDataTable :columns="columns" :data="tableData" :pagination="false" :bordered="false" flex-height
                style="height: 100%;" />
        </div>
        <div class="interpreter_record_pagination">
            <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
                :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
                :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
                @update:page-size="paginationReactive.onUpdatePageSize">
                <template #suffix>页</template>
                <template #prefix>
                    <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </div>
    </div>
    <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
        <VDialogContent @close="modalVisible = false" @submit="revoke" title="撤回提示">
            <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
                您确定撤回吗？
            </div>
        </VDialogContent>
    </NModal>
</template>

<style scoped lang="scss">
.interpreter_record_container {
    height: 100%;
    padding: 30rem;

    .interpreter_record_form {
        height: 7%;
    }

    .interpreter_record_table {
        height: 87%;
    }

    .interpreter_record_pagination {
        height: 6%;
    }
}
</style>
